package com.zb.frame.modules.sys.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zb.frame.base.model.MPPage;
import com.zb.frame.base.model.R;
import com.zb.frame.modules.common.controller.AbstractController;
import com.zb.frame.modules.monitor.enums.LogModule;
import com.zb.frame.modules.monitor.enums.LogType;
import com.zb.frame.modules.monitor.service.LogService;
import com.zb.frame.modules.sys.entity.RelUserRole;
import com.zb.frame.modules.sys.entity.User;
import com.zb.frame.modules.sys.service.RelUserRoleService;
import com.zb.frame.modules.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bangZZ
 * @since 2020-06-04
 */
@RestController
@RequestMapping("/sys/user")
public class UserController extends AbstractController{

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;

    @Autowired
    RelUserRoleService userRoleService;

    @Autowired
    LogService logService;


    @ApiOperation(value = "getUsers", notes = "获取所有用户列表信息")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "page", value = "当前页数", dataType = "String"),
        @ApiImplicitParam(name = "limit", value = "一页显示数量", dataType = "String"),
        @ApiImplicitParam(name = "name", value = "登录账号/用户别名", dataType = "String"),
        @ApiImplicitParam(name = "type", value = "用户状态", dataType = "String")
    })
    @GetMapping("/list")
    @RequiresPermissions("sys:user:view")
    public R getUsers(Integer page, Integer limit,String name, Integer type) {
        Integer currPage = (page == null) ? 1 : page;
        Integer pageSize = (limit == null) ? 10 : limit;
        Page<User> pageInfo = new Page<>(currPage, pageSize);
        Map<String, Object> query = new HashMap<>();
        query.put("name", name);
        query.put("type", type);
        MPPage retData = userService.getUserList(pageInfo, query);
        return R.ok(retData);
    }

    @ApiOperation(value = "getUser", notes = "根据用户Id获取所有用户信息")
    @ApiImplicitParam(name = "id", value = "用户Id", dataType = "Number")
    @GetMapping("/info/{id}")
    @RequiresPermissions("sys:user:view")
    public R getUser(@PathVariable Long id) {
        User user = userService.getUser(id);
        return (user != null) ? R.ok(user) : R.error(404, "","失败，用户不存在！");
    }


    @ApiOperation(value = "newUser", notes = "新增用户")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "userName", value = "登录账号", dataType = "String"),
        @ApiImplicitParam(name = "userPassword", value = "用户密码", dataType = "String"),
        @ApiImplicitParam(name = "userAlias", value = "用户别名", dataType = "String"),
        @ApiImplicitParam(name = "userPhone", value = "手机号码", dataType = "String"),
        @ApiImplicitParam(name = "userEmail", value = "邮箱", dataType = "String"),
        @ApiImplicitParam(name = "userAvatar", value = "头像url地址", dataType = "String"),
        @ApiImplicitParam(name = "userSex", value = "性别", dataType = "Number"),
        @ApiImplicitParam(name = "userDesc", value = "用户描述", dataType = "String")
    })
    @PostMapping("/info")
    @RequiresPermissions("sys:user:add")
    public R newUser(@RequestBody User data) {
        boolean isExist = userService.isExistUserName(data);
        if (isExist)
            return R.error("失败，登录账号已存在！");
        User user = userService.addUser(data, this.getUserId());
        if (user != null) {
            RelUserRole userRole = new RelUserRole();
            userRole.setUserId(user.getUserId());
            userRole.setRoleId("USER"); // 所有用户赋予角色[普通用户]
            userRoleService.save(userRole);
            // 添加日志
            String newValue = JSON.toJSONString(user);
            logService.addLog(LogModule.SYSUSER, LogType.ADD,"", newValue, String.valueOf(user.getUserId()), this.getUserId(),"新增用户账号[" + user.getUserName() + "]成功，并授普通用户角色");
            return R.ok("成功！",user.getUserId());
        } else {
            return R.error("失败！");
        }
    }

    @ApiOperation(value = "updateUser", notes = "修改用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "登录账号", dataType = "String"),
            @ApiImplicitParam(name = "userAlias", value = "用户别名", dataType = "String"),
            @ApiImplicitParam(name = "userPhone", value = "手机号码", dataType = "String"),
            @ApiImplicitParam(name = "userEmail", value = "邮箱", dataType = "String"),
            @ApiImplicitParam(name = "userAvatar", value = "头像url地址", dataType = "String"),
            @ApiImplicitParam(name = "userSex", value = "性别", dataType = "Number"),
            @ApiImplicitParam(name = "userDesc", value = "用户描述", dataType = "String")
    })
    @PutMapping("/info/{id}")
    @RequiresPermissions("sys:user:edit")
    public R updateUser(@PathVariable Long id, @RequestBody User data) {
        User user = userService.getUser(id);
        if (user == null)
            return R.error("失败，不存在此用户！");
        if (!user.getUserName().equals(data.getUserName())) {
            if (userService.isExistUserName(data))
                return R.error("失败，登录账号已存在！");
        }
        String oldValue = JSON.toJSONString(user);
        String oldName = user.getUserName();
        User userNew = userService.updateUser(user, data);
        if (userNew == null)
            return R.error("失败！");
        String newValue = JSON.toJSONString(userNew);
        String newName = userNew.getUserName();
        // 添加日志
        String msg = oldName.equals(userNew.getUserName())  ? "修改用户账号[" + oldName + "]成功" : "修改用户账号[" + oldName + "]->[" + newName + "]成功";
        logService.addLog(LogModule.SYSUSER, LogType.UPDATE, oldValue, newValue, String.valueOf(user.getUserId()), this.getUserId(), msg);
        return R.ok("成功！");
    }

    @ApiOperation(value = "updateStatus", notes = "停/启用用户")
    @ApiImplicitParam(name = "status", value = "用户状态", dataType = "Number")
    @PutMapping("/status/{id}")
    @RequiresPermissions("sys:user:switch")
    public R updateStatus(@PathVariable Long id, @RequestBody Map<String, Object> data) {
        Integer status = (Integer) data.get("status");
        if (status == 2)
            return R.error("失败！");
        boolean f = userService.changeStatus(id, status);
        if (f) {
            // 添加日志
            boolean type = (status == 1) ? true : false;
            if (type) {
                logService.addLog(LogModule.SYSUSER, LogType.UP, "0", "1", String.valueOf(id), this.getUserId(),"启用用户Id[" + id +"]成功");
            } else {
                logService.addLog(LogModule.SYSUSER, LogType.DOWN, "1", "0", String.valueOf(id), this.getUserId(),"停用用户Id[" + id +"]成功");
            }
            return R.ok("成功！");
        } else {
            return R.error("失败，不存在此用户！");
        }
    }

    @PutMapping("/auth/{id}")
    @RequiresPermissions("sys:user:auth")
    public R authMenu(@PathVariable Long id, @RequestBody Map<String, List<String>> data) {
        List<String> add = data.get("add");
        List<String> del = data.get("remove");
        List<RelUserRole> addList = new ArrayList<>();
        for (String s : add) {
            RelUserRole rel = new RelUserRole();
            rel.setRoleId(s);
            rel.setUserId(id);
            addList.add(rel);
        }
        try {
            if (add.size() > 0) {
                userRoleService.addRelBatch(addList);
                // 添加日志
                logService.addLog(LogModule.SYSUSER, LogType.AUTH, "", ArrayUtils.toString(add), String.valueOf(id), this.getUserId(), "授权成功");
            }
            if (del.size() > 0) {
                userRoleService.deleteByUserIdAndRoleIds(id, del);
                // 添加日志
                logService.addLog(LogModule.SYSUSER, LogType.UNAUTH, ArrayUtils.toString(del), "", String.valueOf(id), this.getUserId(), "取消授权成功");
            }
            return R.ok("成功！");
        } catch (Exception e) {
            return R.error("失败！");
        }
    }

    @GetMapping("/relRole/{id}")
    @RequiresPermissions("sys:role:view")
    public R getUserRelRole(@PathVariable Long id) {
        List<String> data = userRoleService.getRoleIdsByUserId(id);
        return R.ok(data);
    }

}
